package com.airS.task.fileMgr.controller.gk;

import com.airS.task.fileMgr.common.anno.Invoke;
import com.airS.task.fileMgr.common.em.LogType;
import com.airS.task.fileMgr.common.page.Page;
import com.airS.task.fileMgr.common.response.BaseResponse;
import com.airS.task.fileMgr.common.response.ResponseCode;
import com.airS.task.fileMgr.controller.base.SupportController;
import com.airS.task.fileMgr.model.gk.Employee;
import com.airS.task.fileMgr.query.gk.EmployeeQuery;
import com.airS.task.fileMgr.security.shiro.realm.SystemAuthorizingRealm;
import com.airS.task.fileMgr.service.gk.EmployeeService;
import com.airS.task.fileMgr.utils.bean.BeanUtils;
import com.airS.task.fileMgr.utils.collection.CollectionUtils;
import com.airS.task.fileMgr.utils.shiro.SecurityUtils;
import com.airS.task.fileMgr.utils.url.UrlUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * 人员管理
 * Created by alan on 2017/3/17.
 */
@Controller
@RequestMapping("/emp")
public class EmployeeController extends SupportController {

    private Logger logger = LoggerFactory.getLogger(EmployeeController.class);

    @Autowired
    private EmployeeService employeeService;

    /**
     * 人员列表
     * @param employeeQuery
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping("/list")
    public String list(EmployeeQuery employeeQuery, HttpServletRequest request, ModelMap modelMap){
        employeeQuery.setRequestUrl(UrlUtils.getLookupPathForRequest(request));
        Page<Employee> employeePage =  employeeService.queryEmployees(employeeQuery);
        modelMap.put("employeePage", employeePage);
        return "admin/modules/gk/employee_list";
    }

    /**
     * 人员删除
     * @param employeeIds
     * @return
     */
    @RequestMapping("/remove")
    @ResponseBody
    public Object remove(@RequestParam("employeeIds[]") List<Integer> employeeIds){
        BaseResponse baseResponse = new BaseResponse();
        SystemAuthorizingRealm.Principal principal = SecurityUtils.getPrincipal();
        // 数据有效性检查
        if(employeeIds == null || employeeIds.isEmpty()){
            baseResponse.setCode(ResponseCode.PARAM_FAIL);
            baseResponse.setMsg("参数异常，请重试");
            return baseResponse;
        }
        // 人员删除
        Integer count = employeeService.delEmployeeByIds(employeeIds);
        if(count > 0){
            baseResponse.setMsg("删除成功");
        }else{
            baseResponse.setMsg("删除失败，请重试");
            baseResponse.setCode(ResponseCode.BUSINESS_FAIL);
        }
        return baseResponse;
    }

    /**
     * 人员新增页面
     * @param modelMap
     * @return
     */
    @RequestMapping("/toAdd")
    public String toAdd(ModelMap modelMap){
        modelMap.put("employee", new Employee());
        return "admin/modules/gk/employee_add";
    }

    /**
     * 人员新增
     * @param employee
     * @return
     */
    @RequestMapping("/add")
    public String add(Employee employee, HttpSession session){
        BaseResponse baseResponse = new BaseResponse();
        SystemAuthorizingRealm.Principal principal = SecurityUtils.getPrincipal();
        session.removeAttribute("empBaseResponse");
        // 数据校验
        if(BeanUtils.checkParamIsNull(employee.getAccount(), employee.getEmployeeName(),
                employee.getGroupName(), employee.getPassword(), employee.getType())){
            baseResponse.setCode(ResponseCode.PARAM_FAIL);
            session.setAttribute("empBaseResponse", baseResponse);
            return "redirect:/emp/toAdd";
        }
        // 人员新增
        EmployeeQuery employeeQuery = new EmployeeQuery();
        employeeQuery.setAccount(employee.getAccount());
        Page<Employee> employeePage = employeeService.queryEmployees(employeeQuery);
        if(CollectionUtils.isNotEmpty(employeePage.getList())){
            baseResponse.setCode(ResponseCode.REPEAT_FAIL);
            baseResponse.setMsg("该账号已被占用，请重试");
            session.setAttribute("empBaseResponse", baseResponse);
            return "redirect:/emp/toAdd";
        }

        String pwdHashHex = new Md5Hash(new Md5Hash(employee.getPassword()).toHex()).toHex();
        String password = new Sha256Hash(pwdHashHex, employee.getAccount()).toString();

        // 加密
        employee.setPassword(password);

        employee.setUpdatePeople(null);
        employee.setUpdateTime(null);
        employee.setCreateTime(new Date());
        employee.setCreatePeople(principal.getEmployeeName());
        Integer employeeId = employeeService.addEmployee(employee);
        // 封装业务操作状态
        if(employeeId > 0){
            baseResponse.setMsg("操作成功");
        }else{
            baseResponse.setCode(ResponseCode.BUSINESS_FAIL);
            baseResponse.setMsg("操作失败，请重试");
        }
        session.setAttribute("empBaseResponse", baseResponse);
        return "redirect:/emp/list?pclass=p_6&currentClass=c_7";
    }

    /**
     * 人员修改页面
     * @param modelMap
     * @param query
     * @param session
     * @return
     */
    @RequestMapping("/toModify")
    public String toModify(ModelMap modelMap, EmployeeQuery query, HttpSession session){
        BaseResponse baseResponse = new BaseResponse();
        session.removeAttribute("empBaseResponse");
        // 数据有效性检查
        if(query.getEmployeeId() == null){
            baseResponse.setCode(ResponseCode.PARAM_FAIL);
            baseResponse.setMsg("参数异常，请重试");
            session.setAttribute("empBaseResponse", baseResponse);
            return "redirect:/emp/list?pclass=p_6&currentClass=c_7";
        }
        // 封装页面模型
        Employee employee = employeeService.queryEmployeeById(query.getEmployeeId());
        if(employee.getEmployeeId() == null || employee.getEmployeeId() <= 0){
            baseResponse.setCode(ResponseCode.NOT_EXIST_FAIL);
            baseResponse.setMsg("查找不到当前人员，请重试");
            session.setAttribute("empBaseResponse", baseResponse);
            return "redirect:/emp/list?pclass=p_6&currentClass=c_7";
        }
        modelMap.put("employee", employee);
        return "admin/modules/gk/employee_modify";
    }

    /**
     * 人员修改
     * @param employee
     * @param modelMap
     * @param session
     * @return
     */
    @RequestMapping("/modify")
    public String modify(Employee employee, ModelMap modelMap, HttpSession session){
        BaseResponse baseResponse = new BaseResponse();
        SystemAuthorizingRealm.Principal principal = SecurityUtils.getPrincipal();
        session.removeAttribute("empBaseResponse");
        // 数据有效性检查
        if(employee.getEmployeeId() == null){
            baseResponse.setCode(ResponseCode.PARAM_FAIL);
            baseResponse.setMsg("参数异常，请重试");
            session.setAttribute("empBaseResponse", baseResponse);
            return "redirect:/emp/list?pclass=p_6&currentClass=c_7";
        }
        // 人员修改
        employee.setAccount(null);
        employee.setPassword(null);
        employee.setCreateTime(null);
        employee.setCreatePeople(null);
        employee.setUpdatePeople(principal.getEmployeeName());
        employee.setUpdateTime(new Date());
        Integer count = employeeService.updateEmployeeById(employee);
        // 封装业务操作状态
        if(count > 0){
            baseResponse.setMsg("操作成功");
        }else{
            baseResponse.setCode(ResponseCode.BUSINESS_FAIL);
            baseResponse.setMsg("操作失败，请重试");
        }
        session.setAttribute("empBaseResponse", baseResponse);
        return "redirect:/emp/list?pclass=p_6&currentClass=c_7";
    }

    /**
     * 获取操作结果
     * @param session
     * @return
     */
    @RequestMapping("/getOperaStatus")
    @ResponseBody
    public Object getOperaStatus( HttpSession session){
        Object status = session.getAttribute("empBaseResponse");
        session.removeAttribute("empBaseResponse");
        return status;
    }
    
}
